package controller

import (
	. "webGin/models"
	"github.com/gin-gonic/gin"
	"webGin/untils"
	"fmt"
)

func Lists(c *gin.Context) {
	id,err := untils.GetUserId(c)
	if err  != nil {
		fmt.Println("err lists:",err)
	}
	fmt.Println("get id :",id)
	rs, err := GetLists()
	if err != nil {
		ErrJsonRes(1005, err.Error(), c)
		return
	}
	OKJsonRes(gin.H{"lists": rs}, c)
}

func Register(c *gin.Context) {
	var reg User
	if err := c.BindJSON(&reg); err != nil {
		ErrJsonRes(1004, err.Error(), c)
		return
	}
	reg.Password = untils.Md5Encode(reg.Password)
	id, err := reg.Add()
	if err != nil {
		ErrJsonRes(1005, err.Error(), c)
		return
	}
	OKJsonRes(gin.H{"id": id}, c)
}

func Login(c *gin.Context) {
	var req User
	if err := c.BindJSON(&req); err != nil {
		ErrJsonRes(1004, err.Error(), c)
		return
	}
	user, err := req.Info(req)
	if err != nil {
		ErrJsonRes(1005, err.Error(), c)
		return
	}
	if untils.Md5Check(req.Password,user.Password) {
		token,err := untils.CreateToken(user.Id)
		if err != nil {
			ErrJsonRes(1005,err.Error(),c)
			return
		}
		OKJsonRes(gin.H{"info": user,"access_token":token}, c)
	}else {
		ErrJsonRes(1002,"account or password error",c)
		return
	}
}


func Refresh(c *gin.Context) {
	t,err :=untils.RefreshToken(c)
	if err != nil {
		ErrJsonRes(1006,err.Error(),c)
		return
	}
	OKJsonRes(gin.H{"access_token":t},c)
}